package dy.com.udp.单播;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPProvider {
    public static void main(String[] args) throws IOException {
        System.out.println("UDP provider start");
        //作为接收者,设置监听端口
        DatagramSocket ds = new DatagramSocket(20000);

        final byte[] buffer = new byte[512];
        //接收实体
        DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
        ds.receive(dp);

        //获得ip
        String ip  = dp.getAddress().getHostAddress();

        int port = dp.getPort();
        int dataLen = dp.getLength();
        String data = new String(dp.getData(),0,dataLen);
        System.out.println("我是 provider，接收到来自"+ip+"地址，端口号为："+port+"，内容为："+data);
        //构建回送信息
        String response = "Receive data with length: "+dataLen;
        byte[] res = response.getBytes();
        //构建packet
        DatagramPacket responsePacket = new DatagramPacket(res,res.length,dp.getAddress(),dp.getPort());
        ds.send(responsePacket);

        System.out.println("provider已经回传信息，结束");
        ds.close();
    }
}
